package com.jingge.home.configuration;

import com.jingge.home.framework.AiMsgHandler;
import com.jingge.home.framework.CommandMsgHandler;
import com.jingge.home.framework.MoreMsgHandler;
import com.jingge.home.util.LocalCacheManager;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import me.chanjar.weixin.cp.message.WxCpMessageRouter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author Yongxiang
 * @date 2025-06-04 14:06
 * @email 1158055613@qq.com
 */
@Configuration
public class JingGeHomeApplicationConfiguration {
	@Value("${wechat.corpId}")
	private String corpId;

	@Value("${wechat.token}")
	private String token;

	@Value("${wechat.aesKey}")
	private String aesKey;

	@Bean
	public WxCpService wxCpService(WxCpConfigStorage wxCpConfigStorage) {
		WxCpService wxCpService=new WxCpServiceImpl();
		wxCpService.setWxCpConfigStorage(wxCpConfigStorage);
		return wxCpService;
	}

	@Bean
	public WxCpConfigStorage wxCpConfigStorage() {
		WxCpDefaultConfigImpl configStorage = new WxCpDefaultConfigImpl();
		configStorage.setCorpId(corpId);
		configStorage.setToken(token);
		configStorage.setAesKey(aesKey);
		return configStorage;
	}

	@Bean
	public WxCpMessageRouter router(WxCpService wxCpService,
	                                AiMsgHandler aiMsgHandler,
	                                CommandMsgHandler commandMsgHandler,
	                                MoreMsgHandler moreMsgHandler) {
		WxCpMessageRouter router = new WxCpMessageRouter(wxCpService);
		router.rule().rContent("^(a:|c:|@|#).*").handler(commandMsgHandler).async(false).end().rule().content("m")
				.async(false).handler(moreMsgHandler).end().rule()
				.async(false).msgType("text").handler(aiMsgHandler).end().rule()
				.async(false).msgType("image").handler(aiMsgHandler).end();
		return router;
	}

	@Bean
	public LocalCacheManager<String, String> msgCache() {
		return LocalCacheManager.builder().setEntriesExpiration(true).setMaxLength(100000)
		                        .setExpiringTime(10, TimeUnit.MINUTES).build();
	}

	@Bean
	public ThreadPoolExecutor msgHandlePool() {
		return new ThreadPoolExecutor(3, 10, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(20));
	}
}
